package lemon.kenhnhacvn;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;

import saucaca.Object.SongObject;
import saucaca.Service.MusicService;
import saucaca.Util.CMD;
import saucaca.Util.TagName;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.text.InputType;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Toast;


public class BaseEngine {
	public static String encryptMD5(String input) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] messageDigest = md.digest(input.getBytes());
			BigInteger number = new BigInteger(1, messageDigest);
			String hashtext = number.toString(16);
			while (hashtext.length() < 32) {
				hashtext = "0" + hashtext;
			}
			return hashtext;
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		}
	}

	public static boolean isWifiConnected(Context context) {
		ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		return ((netInfo != null) && netInfo.isConnected());
	}

	public static boolean isMobileConnected(Context context) {
		ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		return ((netInfo != null) && netInfo.isConnected());
	}

	public static boolean compareList(ArrayList<SongObject> ls1, ArrayList<SongObject> ls2) {
		if (ls1 != null && ls2 != null) {
			if (ls1.size() < ls2.size() || ls1.size() > ls2.size())
				return false;
			else
				return ls1.toString().contentEquals(ls2.toString()) ? true : false;
		} else
			return false;
	}

	public static String checkVideoPath(String path) {
		return path.replaceAll(" ", "%20");
	}

	public static boolean isConnectionAvailable(Context context) {

		ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivityManager != null) {
			NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo();
			if (netInfo != null && netInfo.isConnected() && netInfo.isConnectedOrConnecting() && netInfo.isAvailable()) {
				return true;
			}
		}
		return false;
	}
	
	
//	public static  String BitmapTobase64(Context context,Bitmap bitmap) {
//		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();  
//		bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
//		byte[] byteArray = byteArrayOutputStream .toByteArray();
//		return Base64.encodeToString(byteArray, Base64.DEFAULT);
//	}
	@SuppressWarnings("unused")
	public static String BitmapTobase64(Bitmap bm) {
		  ByteArrayOutputStream baos = new ByteArrayOutputStream();

		  bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
		  byte[] byteArrayImage = baos.toByteArray();
		  String encodedImage = Base64.encodeToString(byteArrayImage,
		    Base64.DEFAULT);
		  return encodedImage;
		 }
	public static Bitmap BitmapFromBase64(String input) 
	{
	    byte[] decodedByte = Base64.decode(input, 0);
	    return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length); 
	}
	
	public static  void shareTextUrl(Context context,String name,String url) {
	    Intent share = new Intent(android.content.Intent.ACTION_SEND);
	    share.setType("text/plain");
	    share.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
	    share.putExtra(Intent.EXTRA_SUBJECT, name);
	    share.putExtra(Intent.EXTRA_TEXT, url);
	    context.startActivity(Intent.createChooser(share, "Share link!"));
	}

	@TargetApi(Build.VERSION_CODES.FROYO)
	public static final void getKeyHashes(Context context) {
		PackageInfo packageInfo;
		try {
			// packageInfo =
			// getPackageManager().getPackageInfo("casino.vn",PackageManager.GET_SIGNATURES);
			packageInfo = context.getPackageManager().getPackageInfo(context.getPackageManager().getPackageInfo(context.getPackageName(), 0).packageName,
					PackageManager.GET_SIGNATURES);
			for (Signature signature : packageInfo.signatures) {
				MessageDigest md = MessageDigest.getInstance("SHA");
				md.update(signature.toByteArray());
				String key = new String(Base64.encode(md.digest(), 0));
				// String key = new String(Base64.encodeBytes(md.digest()));
				Log.e("Hash key", key);
			}
		} catch (NameNotFoundException e1) {
			Log.e("Name not found", e1.toString());
		} catch (NoSuchAlgorithmException e) {
			Log.e("No such an algorithm", e.toString());
		} catch (Exception e) {
			Log.e("Exception", e.toString());
		}
	}

	public static String convertStringLongtoInteger(String id) {
		String s = "";
		try {
			int x = (int) Float.parseFloat(id);
			s = Integer.toString(x);
		} catch (Exception e) {

		}
		return s;
	}

	public static String getSex(String sex){
		String str=convertStringLongtoInteger(sex);
		if(str.equals("1"))
			return "Nữ";
		if(str.equals("2"))
			return "Đồng tính";
		return "Nam";
		
	}
	public static void setVideoclick(final Context context, View v, final SongObject item) {
		v.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent i = new Intent();
				i.setAction(MusicService.ACTION_PAUSE);
				context.startService(i);
				Intent intent = new Intent(context, VideoPlayActivity.class);
				intent.putExtra(MainActivity.ID, item);
				context.startActivity(intent);
			}
		});
	}
	public static void setVideoclick(final Context context, final SongObject item) {
		Intent i = new Intent();
		i.setAction(MusicService.ACTION_PAUSE);
		context.startService(i);
		Intent intent = new Intent(context, VideoPlayActivity.class);
		intent.putExtra(MainActivity.ID, item);
		context.startActivity(intent);
	}

	public static String loadJSONFromAsset(Context context, String fileName) {
		String json = null;
		try {

			InputStream is = context.getAssets().open(fileName);

			int size = is.available();

			byte[] buffer = new byte[size];

			is.read(buffer);

			is.close();

			json = new String(buffer, "UTF-8");

		} catch (IOException ex) {
			ex.printStackTrace();
			return null;
		}
		return json;

	}

	public static void sendSMS(Context context, String phoneNumber, String message) {
		Log.i("Send SMS", "");
		Intent smsIntent = new Intent(Intent.ACTION_VIEW);
		smsIntent.setType("vnd.android-dir/mms-sms");
		// smsIntent.setData(Uri.parse("smsto:"));
		smsIntent.putExtra("address", phoneNumber);
		smsIntent.putExtra("sms_body", message);
		try {
			context.startActivity(smsIntent);
			Log.i("Finished sending SMS...", "");
		} catch (android.content.ActivityNotFoundException ex) {
			Toast.makeText(context, "SMS faild, please try again later.", Toast.LENGTH_SHORT).show();
		}
	}
	public static void installRingtone(final Context mContext,final String maso,final String cuphapTai,final String cuphapTang,final String dauso){
		String title=mContext.getResources().getString(R.string.ringtone_dialog_content);
		String content="";
		String tai="Cài nhạc chờ soạn:\n"+cuphapTai+" "+maso+" gửi "+dauso;
		String tang="\n\nTặng nhạc chờ soạn:\n"+cuphapTang+" "+maso + " Sđt_nhận"+" gửi "+dauso;
		content+=tai+tang;
		new AlertDialog.Builder(mContext).setTitle(title).setMessage(content).setCancelable(true)
				.setNeutralButton("Hủy", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				}).setPositiveButton(mContext.getResources().getString(R.string.ringtone_gift), new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						BaseEngine.sendSMS_Gift(mContext, dauso, maso,cuphapTang);
						dialog.cancel();
					}
				}).setNegativeButton(mContext.getResources().getString(R.string.ringtone_install), new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						BaseEngine.sendSMS(mContext, dauso, cuphapTai+" "+maso);
						dialog.cancel();
					}
				}).setIcon(android.R.drawable.ic_dialog_info).show();
	}
	public static void sendSMS_Gift(final Context context, final String addressNum, final String codeInstall,final String cuphap) {
		AlertDialog.Builder builder = new Builder(context);
		builder.setTitle(context.getResources().getString(R.string.ringtone_numFriend));
		final EditText tv = new EditText(context);
		tv.setHint("Số điện thoại");
		tv.setInputType(InputType.TYPE_CLASS_PHONE);
		builder.setView(tv);
		builder.setPositiveButton("OK", new android.content.DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				String phone = tv.getText().toString();
				sendSMS(context, addressNum, cuphap+" "+codeInstall + " " + phone );
			}
		});
		builder.setNegativeButton("Cancel", new android.content.DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		builder.create().show();
	}

	public static void showLogformLongString(String str) {
		String ERR = "showLogformLongString";
		if (str != null)
			if (str.length() > 4000) {
				Log.e(ERR, "str.length = " + str.length());
				int chunkCount = str.length() / 4000; // integer division
				for (int i = 0; i <= chunkCount; i++) {
					int max = 4000 * (i + 1);
					if (max >= str.length()) {
						Log.e(ERR, "chunk " + i + " of " + chunkCount + ":" + str.substring(4000 * i));
					} else {
						Log.e(ERR, "chunk " + i + " of " + chunkCount + ":" + str.substring(4000 * i, max));
					}
				}
			} else {
				Log.e(ERR, str.toString());
			}
	}

	public static final String getRequest(Context context, String strRequet) {
		String TAG = "REQUEST_SERVER";
		int code = Integer.parseInt(strRequet);
		switch (code) {
		case 0:
			TagName.showLogError(TAG, strRequet + ":" + CMD.REQUEST_0);
			return CMD.REQUEST_0;
		case 10:
			TagName.showLogError(TAG, strRequet + ":" + CMD.REQUEST_10);
			return CMD.REQUEST_10;
		case 11:
			TagName.showLogError(TAG, strRequet + ":" + CMD.REQUEST_11);
			return CMD.REQUEST_11;
		case 100:
			TagName.showLogError(TAG, strRequet + ":" + CMD.REQUEST_100);
			return CMD.REQUEST_100;
		case 101:
			TagName.showLogError(TAG, strRequet + ":" + CMD.REQUEST_101);
			return CMD.REQUEST_101;
		case 102:
			TagName.showLogError(TAG, strRequet + ":" + CMD.REQUEST_102);
			return CMD.REQUEST_102;
		case 103:
			TagName.showLogError(TAG, strRequet + ":" + CMD.REQUEST_103);
			return CMD.REQUEST_103;
		case 104:
			TagName.showLogError(TAG, strRequet + ":" + CMD.REQUEST_104);
			return CMD.REQUEST_104;
		case 105:
			TagName.showLogError(TAG, strRequet + ":" + CMD.REQUEST_105);
			return CMD.REQUEST_105;
		case 106:
			TagName.showLogError(TAG, strRequet + ":" + CMD.REQUEST_106);
			return CMD.REQUEST_106;
		case 107:
			TagName.showLogError(TAG, strRequet + ":" + CMD.REQUEST_107);
			return CMD.REQUEST_107;
		case 108:
			TagName.showLogError(TAG, strRequet + ":" + CMD.REQUEST_108);
			return CMD.REQUEST_108;
		case 110:
			TagName.showLogError(TAG, strRequet + ":" + CMD.REQUEST_110);
			return CMD.REQUEST_110;
		case 111:
			TagName.showLogError(TAG, strRequet + ":" + CMD.REQUEST_111);
			return CMD.REQUEST_111;
		case 1101:
			TagName.showLogError(TAG, strRequet + ":" + CMD.REQUEST_1101);
			return CMD.REQUEST_1101;
		case 1102:
			TagName.showLogError(TAG, strRequet + ":" + CMD.REQUEST_1102);
			return CMD.REQUEST_1102;
		case 1103:
			TagName.showLogError(TAG, strRequet + ":" + CMD.REQUEST_1103);
			return CMD.REQUEST_1103;
		case 1104:
			TagName.showLogError(TAG, strRequet + ":" + CMD.REQUEST_1104);
			return CMD.REQUEST_1104;
		case 1105:
			TagName.showLogError(TAG, strRequet + ":" + CMD.REQUEST_1105);
			return CMD.REQUEST_1105;
		case 113:
			TagName.showLogError(TAG, strRequet + ":" + CMD.REQUEST_113);
			return CMD.REQUEST_113;
		default:
			TagName.showLogError(TAG, strRequet);
			return "";
		}
	}

	public static String[] stringtoArray(String s, String sep) {
		// convert a String s to an Array, the elements
		// are delimited by sep
		// NOTE : for old JDK only (<1.4).
		// for JDK 1.4 +, use String.split() instead
		StringBuffer buf = new StringBuffer(s);
		int arraysize = 1;
		for (int i = 0; i < buf.length(); i++) {
			if (sep.indexOf(buf.charAt(i)) != -1)
				arraysize++;
		}
		String[] elements = new String[arraysize];
		int y, z = 0;
		if (buf.toString().indexOf(sep) != -1) {
			while (buf.length() > 0) {
				if (buf.toString().indexOf(sep) != -1) {
					y = buf.toString().indexOf(sep);
					if (y != buf.toString().lastIndexOf(sep)) {
						elements[z] = buf.toString().substring(0, y);
						z++;
						buf.delete(0, y + 1);
					} else if (buf.toString().lastIndexOf(sep) == y) {
						elements[z] = buf.toString().substring(0, buf.toString().indexOf(sep));
						z++;
						buf.delete(0, buf.toString().indexOf(sep) + 1);
						elements[z] = buf.toString();
						z++;
						buf.delete(0, buf.length());
					}
				}
			}
		} else {
			elements[0] = buf.toString();
		}
		buf = null;
		return elements;
	}
}
